package com.papercutting.platform.controller.admin;

import com.papercutting.platform.common.Result;
import com.papercutting.platform.dto.query.CultureQuery;
import com.papercutting.platform.dto.request.CultureRequest;
import com.papercutting.platform.dto.response.CultureResponse;
import com.papercutting.platform.dto.response.PageResult;
import com.papercutting.platform.service.CultureService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

/**
 * 管理员-剪纸文化控制器
 */
@Slf4j
@RestController("adminCultureController")
@RequestMapping("/api/admin/culture")
@RequiredArgsConstructor
@Validated
public class CultureController {
    
    private final CultureService cultureService;
    
    /**
     * 创建文化内容
     */
    @PostMapping
    public Result<Long> createCulture(@Valid @RequestBody CultureRequest request) {
        log.info("创建文化内容请求: {}", request.getTitle());
        
        Long cultureId = cultureService.createCulture(request);
        
        return Result.success("文化内容创建成功", cultureId);
    }
    
    /**
     * 更新文化内容
     */
    @PutMapping("/{id}")
    public Result<Void> updateCulture(
            @PathVariable @NotNull Long id,
            @Valid @RequestBody CultureRequest request) {
        log.info("更新文化内容请求: {}", id);
        
        request.setId(id);
        cultureService.updateCulture(request);
        
        return Result.success("文化内容更新成功");
    }
    
    /**
     * 删除文化内容
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteCulture(@PathVariable @NotNull Long id) {
        log.info("删除文化内容请求: {}", id);
        
        cultureService.deleteCulture(id);
        
        return Result.success("文化内容删除成功");
    }
    
    /**
     * 获取文化内容详情
     */
    @GetMapping("/{id}")
    public Result<CultureResponse> getCultureDetail(@PathVariable @NotNull Long id) {
        log.info("获取文化内容详情: {}", id);
        
        CultureResponse culture = cultureService.getCultureById(id);
        
        return Result.success(culture);
    }
    
    /**
     * 分页查询文化内容列表
     */
    @GetMapping("/page")
    public Result<PageResult<CultureResponse>> getCulturePage(CultureQuery query) {
        log.info("分页查询文化内容列表: {}", query);
        
        PageResult<CultureResponse> result = cultureService.getCulturePage(query);
        
        return Result.success(result);
    }
    
    /**
     * 获取文化内容列表（不分页）
     */
    @GetMapping("/list")
    public Result<List<CultureResponse>> getCultureList(CultureQuery query) {
        log.info("查询文化内容列表: {}", query);
        
        List<CultureResponse> result = cultureService.getCultureList(query);
        
        return Result.success(result);
    }
    
    /**
     * 批量删除文化内容
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteCultures(@RequestBody List<Long> ids) {
        log.info("批量删除文化内容: {}", ids);
        
        if (ids == null || ids.isEmpty()) {
            return Result.error("删除列表不能为空");
        }
        
        if (ids.size() > 100) {
            return Result.error("单次批量删除不能超过100项");
        }
        
        cultureService.batchDeleteCultures(ids);
        
        return Result.success(String.format("批量删除成功，共删除 %d 项文化内容", ids.size()));
    }
    
    /**
     * 更新文化内容状态
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateCultureStatus(
            @PathVariable @NotNull Long id,
            @RequestBody Map<String, Object> params) {
        log.info("更新文化内容状态: {} -> {}", id, params);
        
        Integer status = (Integer) params.get("status");
        if (status == null) {
            return Result.error("状态参数不能为空");
        }
        
        cultureService.batchUpdateStatus(List.of(id), status);
        
        return Result.success("状态更新成功");
    }
    
    /**
     * 批量更新状态
     */
    @PutMapping("/batch/status")
    public Result<Void> batchUpdateStatus(@RequestBody Map<String, Object> params) {
        log.info("批量更新状态: {}", params);
        
        @SuppressWarnings("unchecked")
        List<Long> ids = (List<Long>) params.get("ids");
        Integer status = (Integer) params.get("status");
        
        if (ids == null || ids.isEmpty()) {
            return Result.error("ID列表不能为空");
        }
        if (status == null) {
            return Result.error("状态参数不能为空");
        }
        
        cultureService.batchUpdateStatus(ids, status);
        
        return Result.success("批量更新状态成功");
    }
    
    /**
     * 获取统计信息
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getCultureStats() {
        log.info("获取文化内容统计信息");

        CultureQuery query = new CultureQuery();
        List<CultureResponse> allCultures = cultureService.getCultureList(query);

        long totalCount = allCultures.size();
        long publishedCount = allCultures.stream().filter(c -> c.getStatus() == 1).count();
        long draftCount = allCultures.stream().filter(c -> c.getStatus() == 0).count();
        long totalViews = allCultures.stream().mapToLong(c -> c.getViewCount() != null ? c.getViewCount() : 0).sum();

        Map<String, Object> stats = Map.of(
            "totalCount", totalCount,
            "publishedCount", publishedCount,
            "draftCount", draftCount,
            "totalViews", totalViews
        );

        return Result.success(stats);
    }
}
